package com.ruoyi.ws;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ChatWebSocketHandler extends TextWebSocketHandler {
    private static final Map<WebSocketSession, String> sessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        sessions.put(session, "用户" + sessions.size());
        broadcastMessage("系统", sessions.get(session) + " 加入了聊天室");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        String username = sessions.get(session);
        broadcastMessage(username, message.getPayload());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String username = sessions.remove(session);
        broadcastMessage("系统", username + " 离开了聊天室");
    }

    private void broadcastMessage(String sender, String message) {
        String formattedMessage = String.format("[%s] %s: %s",
            LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
            sender, message);

        sessions.keySet().forEach(session -> {
            try {
                session.sendMessage(new TextMessage(formattedMessage));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
